package models

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"encoding/json"
	"fmt"
)

// DownstreamUserInfo represents the decrypted user information from the header
type DownstreamUserInfo struct {
	UserID   string   `json:"user_id"`
	Username string   `json:"username"`
	Email    string   `json:"email"`
	Roles    []string `json:"roles"`
	IsOwner  bool     `json:"is_owner"`
	IsGuest  bool     `json:"-"` // 非API字段，用于前端判断
}

// GuestUserInfo returns a default user info for guests
func GuestUserInfo() *DownstreamUserInfo {
	return &DownstreamUserInfo{
		Username: "游客",
		Email:    "未登录",
		Roles:    []string{"guest"},
		IsGuest:  true,
	}
}

// DecryptUserInfo decrypts the user information from the encrypted header
func DecryptUserInfo(encryptedHeader string, key []byte) (*DownstreamUserInfo, error) {
	// 解码 hex 字符串
	ciphertext, err := hex.DecodeString(encryptedHeader)
	if err != nil {
		return nil, fmt.Errorf("failed to decode hex string: %v", err)
	}

	// 创建 cipher block
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, fmt.Errorf("failed to create cipher block: %v", err)
	}

	// 提取 IV（前 16 字节）
	if len(ciphertext) < aes.BlockSize {
		return nil, fmt.Errorf("ciphertext too short")
	}
	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]

	// 解密
	stream := cipher.NewCFBDecrypter(block, iv)
	plaintext := make([]byte, len(ciphertext))
	stream.XORKeyStream(plaintext, ciphertext)

	// 解析 JSON
	var userInfo DownstreamUserInfo
	if err := json.Unmarshal(plaintext, &userInfo); err != nil {
		return nil, fmt.Errorf("failed to unmarshal user info: %v", err)
	}

	// 设置非游客标志
	userInfo.IsGuest = false

	return &userInfo, nil
}
